package org.qy.ca.client;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;

/**
 * @Description:	des
 * @Author:		方宇康
 * @CreateDate:	2020/5/18 9:58
 * @Version:      	1.0.0.1
 * @Company:       联通智网科技有限公司
 */
@Slf4j
public class HttpsKeyStoreConnect
{
    /**
     * 客户端证书路径，用了本地绝对路径，需要修改
     */
    private final static String PFX_PATH = "E:\\个人晋升\\CA证书\\client.p12";

    /**
     * 客户端证书密码及密钥库密码
     */
    private final static String PFX_PWD = "123456";

    /**
     * 方法实现说明
     *
     * @param url
     * @return
     * @exception
     * @date        2020/5/18 10:11
     */
    public static String sslRequestGet(String url) throws Exception
    {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        InputStream inputStream = new FileInputStream(new File(PFX_PATH));
        log.info("HttpsKeyStoreConnect|sslRequestGet|", inputStream);
        try
        {
            // 这里就指的是KeyStore库的密码
            keyStore.load(inputStream, PFX_PWD.toCharArray());
        }
        finally {
            inputStream.close();
        }
        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, PFX_PWD.toCharArray()).build();
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext
                // supportedProtocols ,这里可以按需要设置
                , new String[] { "TLSv1", "SSLv3", "TLSv1.1", "TLSv1.2"}
                // supportedCipherSuites
                , null
                , SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
        try
        {
            HttpGet httpget = new HttpGet(url);
            CloseableHttpResponse response = httpclient.execute(httpget);
            try
            {
                HttpEntity entity = response.getEntity();
                // 返回结果
                String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
                EntityUtils.consume(entity);
                return jsonStr;
            }
            finally {
                response.close();
            }
        }
        finally {
            httpclient.close();
        }
    }

    public static void main(String[] args) throws Exception
    {
        log.info("HttpsKeyStoreConnect|main|访问双向认证Tomcat服务请求出参：={}", sslRequestGet("https://www.qy-bb.club"));
    }
}
